package top.byteio.common.oauth2.config;

import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import top.byteio.common.cache.client.JoleRedisClient;
import top.byteio.common.oauth2.cache.RedisStateCache;
import top.byteio.common.oauth2.properties.Oauth2Properties;

/**
 * <p>
 * JustAuth 缓存装配类，{@link Oauth2AutoConfiguration.AuthStateCacheAutoConfiguration}
 * </p>
 *
 * @author lerryxia
 */
@Slf4j
public class Oauth2StateCacheConfiguration {
    /**
     * Redis 缓存
     */
    @ConditionalOnClass(RedisTemplate.class)
    @ConditionalOnMissingBean(AuthStateCache.class)
    @AutoConfigureBefore(RedisAutoConfiguration.class)
    @ConditionalOnProperty(name = "jole.common.oauth2.cache.type", havingValue = "redis", matchIfMissing = true)
    static class Redis {
        static {
            log.info("Jole-Oauth2 使用 Redis 缓存存储 state 数据");
        }

        @Bean
        public AuthStateCache authStateCache(Oauth2Properties oauth2Properties, JoleRedisClient joleRedisClient) {
            return new RedisStateCache( oauth2Properties.getCache(), joleRedisClient);
        }
    }

    /**
     * 默认缓存
     */
    @ConditionalOnMissingBean(AuthStateCache.class)
    @ConditionalOnProperty(name = "jole.common.oauth2.cache.type", havingValue = "default", matchIfMissing = true)
    static class Default {
        static {
            log.info("Jole-Oauth2 使用 默认缓存存储 state 数据");
        }

        @Bean
        public AuthStateCache authStateCache() {
            return AuthDefaultStateCache.INSTANCE;
        }
    }

    /**
     * 默认缓存
     */
    @ConditionalOnProperty(name = "jole.common.oauth2.cache.type", havingValue = "custom")
    static class Custom {
        static {
            log.info("Jole-Oauth2 使用 自定义缓存存储 state 数据");
        }

        @Bean
        @ConditionalOnMissingBean(AuthStateCache.class)
        public AuthStateCache authStateCache() {
            log.error("请自行实现 me.zhyd.oauth.cache.AuthStateCache");
            throw new RuntimeException();
        }
    }
}
